package com.xiang.reflection;

import java.lang.reflect.Constructor;
import java.lang.reflect.Field;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;

public class test08 {
    public static void main(String[] args) throws ClassNotFoundException, IllegalAccessException, InstantiationException, NoSuchMethodException, InvocationTargetException, NoSuchFieldException {

        //获得class对象
        Class c1 = Class.forName("com.xiang.reflection.User");

        //通过反射构造对象
        User user = (User) c1.newInstance();//本质是调用了无参构造器
        System.out.println(user);

        //通过构造器创建对象,先自定义一个构造器，这里是先获取了user的类，然后自己获取类的构造方法，这里属于重载，就是指定参数获取有参构造
        Constructor declaredConstructor = c1.getDeclaredConstructor(String.class, int.class, int.class);
        Object o = declaredConstructor.newInstance("秦疆", 11, 18);
        System.out.println(o);

        //也可以无参数构造
        Constructor declaredConstructor1 = c1.getDeclaredConstructor();
        Object o1 = declaredConstructor1.newInstance();
        System.out.println(o1);

        //通过反射调用普通方法,invoke(对象，"方法的值")
        Method setName = c1.getDeclaredMethod("setName", String.class);
        Method setAge = c1.getDeclaredMethod("setAge",int.class);
        setName.invoke(user,"狂神");
        setAge.invoke(user,12);
        System.out.println(user.getName());
        System.out.println(user.getAge());

        //可以暴力反射。修改私有属性，关闭安全监测
        Field name = c1.getDeclaredField("name");
        name.setAccessible(true);
        name.set(user,"xiang11");
        System.out.println(user.getName());
    }
}
